package com.bianmaba.spring.security.database.configuration;

import com.bianmaba.spring.security.basic.configuration.BasicWebSecurityConfigurerAdapter;
import com.bianmaba.spring.security.database.access.intercept.DatabaseSecurityFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

import static com.bianmaba.spring.security.autoconfig.WebSecurityAutoConfiguration.ORDER;


@Configuration
@ConditionalOnClass({WebSecurityConfigurerAdapter.class})
@ConditionalOnProperty(prefix = "spring.security", name = "type", havingValue = "database")
//如果此类加载前已经存在指定类型的实例，则此类将不会被实例化(如果有继承关系，则可能会执行构造函数，但实际为同一个实例时为正常，否则可能不正常)
@ConditionalOnMissingBean({WebSecurityConfigurerAdapter.class})
@Order(ORDER - 1)//配置初始化排序，此值越低，越靠前，但@Import引入的类此注解无效
@Import(DatabaseSecurityFilter.class)
public class DatabaseWebSecurityConfigurerAdapter extends BasicWebSecurityConfigurerAdapter {
    protected static final Logger LOG = LoggerFactory.getLogger(DatabaseWebSecurityConfigurerAdapter.class);

    @Autowired
    protected DatabaseSecurityFilter filter;

    public DatabaseWebSecurityConfigurerAdapter() {
        if (this.getClass().getName().equals(DatabaseWebSecurityConfigurerAdapter.class.getName())) ;
        {
            LOG.info("加载WEB安全性配置器适配器(order=" + (ORDER - 1) + "):" + this.getClass().getName());
        }
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http.addFilterBefore(filter, FilterSecurityInterceptor.class));
    }

    //处理用户配置的的资源：在数据库管理授权的情况下为ResourceDetailsServices管理
    protected void configureResources(HttpSecurity http) throws Exception {
    }
}
